import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/addmenu/GetSFBMPage.dart';
import 'package:jyofservice/bean/user_fee_info_entity.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/CallRecordNotification.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:jyofservice/util/EncodeUtil.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../util/AssetPicker.dart';

class AddMenuPage extends StatefulWidget {
  @override
  _AddMenuPageState createState() => _AddMenuPageState();
}

class _AddMenuPageState extends State<AddMenuPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool isloading = true;


  TextEditingController _ChuLiTextEditingController = TextEditingController();
  TextEditingController _phoneController = TextEditingController();
  UserFeeInfoDataData? detailEntity;
  String? sfbm = "";
  String? username = "";
  String? address = "";
  StreamSubscription? subscriptionType = null;

  List<String> paths = <String>[];
  List showAssetsList = [];
  List showPhotosList = [];
  List<AssetEntity> assets = <AssetEntity>[];
  bool isDisplayingDetail = true;
  bool positive = true;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    subscriptionType =
        Constants.eventBus.on<MenuNotification>().listen((event) {
          detailEntity = event.data;
          sfbm = detailEntity!.sfbm;
          username = detailEntity!.linkMan;
          address = detailEntity!.allName;
          _phoneController.text = detailEntity!.phone!;
          if (mounted) {
            setState(() {});
          }
        });

    subscriptionType!.resume();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: const Color(0xFFF1F1F1),
      appBar: AppBar(
        centerTitle: true,
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.pop(context, false);
            }),
        actions: <Widget>[
          SizedBox(
            height: ScreenUtil().setHeight(20),
          )
        ],
        title: Text('工单补录',
            //FluroConvertUtils.fluroCnParamsDecode(widget.title),
            style: TextStyle(
                color: Colors.white, fontSize: ScreenUtil().setSp(45))),
      ),
      body: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: ScreenUtil().setHeight(30),
                      ),
                      getRange(),
                      Container(
                        color: Colors.black12,
                        height: ScreenUtil().setHeight(2),
                      ),
                      getUserData('用户姓名', username),
                      Container(
                        color: Colors.black12,
                        height: ScreenUtil().setHeight(2),
                      ),
                      getUserData('用户地址', address),
                      Container(
                        color: Colors.black12,
                        height: ScreenUtil().setHeight(2),
                      ),
                      getUserPhone('联系电话'),
                      Container(
                        color: Colors.black12,
                        height: ScreenUtil().setHeight(2),
                      ),
                      getChuLiNeiRong(),
                      JhAssetPicker(
                        assetType: AssetTypes.image,
                        lineCount: 3,
                        callBack:
                            (assetEntityList, CallBackType type) {
                          if (type == CallBackType.add) {
                            Navigator.pop(context);
                          }
                          print('assetEntityList-------------');
                          print(assetEntityList);
                          print('assetEntityList-------------');

                          assets = assetEntityList;
                          if (mounted) {
                            setState(() {});
                          }
                        },
                      )
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  if (isloading) {
                    //提交报修
                    if(detailEntity==null||_phoneController.text.toString().length<1) {
                      Fluttertoast.showToast(msg: "请将信息填写完成");
                      return;
                    }

                    isloading = false;
                    if (mounted) {
                      setState(() {});
                    }
                    encodeFile();
                  } else {
                    Fluttertoast.showToast(msg: "系统正在加载");
                  }
                },
                child: Container(
                  alignment: Alignment.bottomCenter,
                  color: Colors.blue,
                  width: ScreenUtil().screenWidth,
                  child: Center(
                    child: Text(
                      '提交',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(40)),
                    ),
                  ),
                  height: ScreenUtil().setHeight(100),
                ),
              ),
            ],
          ),
          Offstage(
            offstage: isloading,
            child: SpinKitFadingCircle(
              color: Colors.blue,
              size: 50.0,
            ),
          )
        ],
      ),
      endDrawer: GetSFBMPage(),
    );
  }

  //根据下拉获取收费编码
  Widget getRange() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      height: ScreenUtil().setHeight(100),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '用户编码',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.all(2),
//              height: ScreenUtil().setHeight(80),
              child: Row(
                children: <Widget>[
                  TextButton(
                      onPressed: () {
                        _scaffoldKey.currentState!.openEndDrawer();
                      },
                      child: Container(
                        width: ScreenUtil().setHeight(360),
                        padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                        child: Text(
                          sfbm!.length > 0 ? sfbm! : '请选择',
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil().setSp(30)),
                        ),
                      )),
                ],
              ),
            ),
          ),
          Icon(
            Icons.keyboard_arrow_right,
            color: Color(0xff666666),
          )
        ],
      ),
    );
  }

  //处理内容
  Widget getChuLiNeiRong() {
    return Container(
      padding: EdgeInsets.all(10),
      color: Colors.white,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '*',
            style: TextStyle(color: Colors.red),
          ),
          Expanded(
            flex: 1,
            child: Text(
              '描述信息',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
          Expanded(
              flex: 2,
              child: Container(
                height: ScreenUtil().setWidth(160),
                width: ScreenUtil().setWidth(500),
                color: Color(0xfff2f5f9),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.0, color: Colors.black12),
                    borderRadius: BorderRadius.circular(2.5),
//                                               color: Colors.white,
                  ),
                  child: TextField(
                    textAlign: TextAlign.start,
                    maxLines: null,
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调

                      print('submit $text');
                    },
                    controller: _ChuLiTextEditingController,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
                      fillColor: Color(0xfff2f5f9),
                      contentPadding: EdgeInsets.all(10.0),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }


  Widget getRowData(
      TextEditingController controller, String hint, String title, bool isNum) {
    return Container(
      padding: const EdgeInsets.only(left: 10),
      color: Colors.white,
      width: ScreenUtil().screenWidth,
      height: ScreenUtil().setHeight(120),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '*',
            style: TextStyle(color: Colors.red),
          ),
          Expanded(
            flex: 1,
            child: Text(
              '$title',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 2,
            child: TextField(
              controller: controller,
              style: TextStyle(fontSize: ScreenUtil().setSp(35.0)),
              decoration: InputDecoration(
                hintText: '$hint',
                hintStyle: TextStyle(fontSize: ScreenUtil().setSp(35.0)),
                border: InputBorder.none,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget getUserData(String title, String? messgae) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      color: Colors.white,
      width: ScreenUtil().screenWidth,
      height: ScreenUtil().setHeight(100),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '$title',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 2,
            child: Text(
              '$messgae',
              style: TextStyle(
                  color: Colors.grey, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
        ],
      ),
    );
  }

  Widget getUserPhone(String title) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      color: Colors.white,
      width: ScreenUtil().screenWidth,
      height: ScreenUtil().setHeight(100),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '*',
            style: TextStyle(color: Colors.red),
          ),
          Text(
            '$title',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 2,
            child: TextField(
              controller: _phoneController,
              style: TextStyle(fontSize: ScreenUtil().setSp(35.0)),
              decoration: InputDecoration(
                hintStyle: TextStyle(fontSize: ScreenUtil().setSp(35.0)),
                border: InputBorder.none,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future encodeFile() async {
    var files =[];
    if (assets.length == 0) {
      Fluttertoast.showToast(
        msg:"请至少上传一张照片",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }
      return;
    }
    //附件
    List fileList = [];

    for (int i = 0; i < assets.length; i++) {
      File? file = await assets[i].file;

      //var fileType = file?.path.substring(file.path.lastIndexOf('.') + 1);

      fileList.add(file?.path);
    }

    for (int i = 0; i < fileList.length; i++) {
      //截取字符串作为图片命名
      String fileName =  fileList[i]
          .substring(fileList[i].lastIndexOf("/") + 1, fileList[i].length)
          .toString()
          .replaceAll(" ", "");

      String imagePath = fileList[i];
      String imageBase64;
      await EncodeUtil.image2Base64(imagePath).then((data) {
        imageBase64 = data; //data.replaceAll('+', "%2B");
        print("imageBase64===$imageBase64");

        var str = {"FileName": "$fileName.jpg", "Base64Str": "$imageBase64"};
        files.add(str);
      });
    }
    submitRepair(files);
  }

  //提交报修
  Future submitRepair(List houseList) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    try {
      var data = {
        "key": key,
        "filedata": houseList,
        "ClientType": "phone",
        "ClientKey": aesData
      };
      print("附件提交：" + data.toString());
      Response response = await Dio().post(
          WebConfig().baseUrl + "Public/UploadFile",
          data: data);

      print("response:${response.data}");

      if (response.data["Code"] == "200") {
        var result = response.data["Data"];
//        List fileArrs = new List();
//        for (int i = 0; i < result.length; i++) {
//          String str = result[i]["FileName"];
//          fileArrs.add(str);
//        }
        submitInfo(result);
        print(json.encode(result).toString());
      }else{
        if(mounted) {
          setState(() {
            isloading = true;
          });
        }
      }
    } catch (e) {
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }
      print(e.toString());
    }
  }

  Future submitInfo(List? fileArrs) async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String lsh = await AesUtil.getLSH(sfbm ?? '');
    String aesData = await AesUtil.encodeBase64();
    try {
      var data = {
        "Sfbm": sfbm,
        "Man": username,
        "Phone": _phoneController.text.toString(),
        "Adress": detailEntity!.allName,
        "WantType": 1,
        "Remarks": _ChuLiTextEditingController.text.toString(),
        "FromPhone": "",
        "key": key,
        "ClientType": "SFAPP",
        "ClientKey": aesData,
        "LSH":lsh,
        "fujian": fileArrs,
        "UID": sharedPreferences.getString("id")
      };
      print("附件提交：" + data.toString());
      Response response = await Dio().post(
          WebConfig().baseUrl + "House/RequestHelp",
          data: data);

      print("response:${response.data}");

      if (response.data["Code"] == "200") {
        Fluttertoast.showToast(
          msg:"补录成功",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
        Navigator.of(context).pop();
      }else{
        Fluttertoast.showToast(
          msg: response.data["Msg"].toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
      }
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }
    } catch (e) {
      if(mounted) {
        setState(() {
          isloading = true;
        });
      }
      print(e.toString());
    }

  }
}
